<?php
/*
 * Created on Jul 3, 2009
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
?>
<?php

require_once APPPATH."models/model_dao.php";
class Model_nav extends Model_dao {
	var $_public = 1;
	function Model_nav() {
		// Call the Model constructor
		parent :: Model_dao("tbl_nav");
	}

	function find($id) {
		if (intval($id)) {
			$query = $this->db->get_where($this->_tbl_name, array (
				'id' => $id
			));

			if ($query->num_rows() > 0) {
				return $query->first_row('array');
			}
		}
		return null;

	}

	/**
	 *
	 *
	 */
	function findByIds($ids) {
		$result = array ();
		//echo $this->db->last_query();
		foreach ($ids as $id) {
			$this->db->select("id, nav, head, nodelink");
			$this->db->where("{$this->_tbl_name}.id", $id);
			$query = $this->db->get($this->_tbl_name);
			if ($query->num_rows() > 0) {
				$result[] = $query->first_row('array');
			}
		}
		return $result;
	}
	/**
	 *
	 *
	 *
	 */
	function fetchNav($pid = 0, $sort = 'sort', $type_sort = 'asc', $limit = null, $offset = null, $show_footer=null) {
		$this->db->select('id, pid, level, nav_name, title, url_title, icon, description, target, target_link, css_class, show_footer');
		if (!is_null($pid)) {
			$this->db->where('pid', $pid);
		}
		if (!is_null($show_footer)) {
			$this->db->where('show_footer', $show_footer);
		}
		$this->db->where('publish', $this->_public);
		$this->db->order_by($sort, $type_sort);

		$query = $this->db->get($this->_tbl_name);
		//log_message('error', $this->db->last_query());
		if ($query->num_rows() > 0) {
			$result = $query->result_array();
			foreach($result as $key => $val){
				$result[$key]['children'] = $this->fetchNav($val['id']);
			}
			return $result;
		}
		return null;
	}

	function update($id, $data) {
		$this->db->where('id', $id);
		$this->db->update($this->_tbl_name, $data);
	}

	function get_parent($id){
		$this->db->where('id', $id);
		$query = $this->db->get($this->_tbl_name);
		$result = $query->first_row();
		return $result->pid;

	}

	function get_parent_level($id){
		if(intval($id)){			
			$this->db->where('id', $id);
			$query = $this->db->get($this->_tbl_name);
			$result = $query->first_row();
			if($result->pid == 0)
				return $result->id;
			return $this->get_parent_level($result->pid);
		}
		return null;
	}
}
?>